package util;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.ThreadPoolTaskConfig.ThreadPoolTaskConfig;

import javax.net.ssl.HttpsURLConnection;


public class Request {
//    SqlSession sqlSession=MyBatisUtils.getSqlSession();
//    Access_token access_token=sqlSession.selectOne("mapper.accessMapper.selectAccess");


    private static final Logger log = LoggerFactory.getLogger(Request.class);
    String time = System.currentTimeMillis() / 10 + "";

    public static String joke() {
        Map<String, String> map = new HashMap<>();
        map.put("key", "dc65452c7d8299c992ee875d92669136");
        String url = "http://v.juhe.cn/joke/randJoke.php";
        return sendPost(url, map);
    }

    public static String idiom(String wd) {
        Map<String, Object> map = new HashMap<>();
        String url = "http://apis.juhe.cn/idiomJie/query";
        map.put("key", "8db731da8f9bb01f14a2bf96f66f46c2");
        map.put("wd", wd);
        map.put("size", 1);
        map.put("is_rand", 1);
        return sendPost(url, map);
    }

    public static String sendPost(String url, String data) {
        try {
            URL urlObj = new URL(url);
            URLConnection connection = urlObj.openConnection();
            connection.setDoOutput(true);
            OutputStream os = connection.getOutputStream();
            os.write(data.getBytes(StandardCharsets.UTF_8));
            os.close();
            InputStream is = connection.getInputStream();
            byte[] b = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = is.read(b)) != -1) {
                sb.append(new String(b, 0, len));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String sendPost(String url, Map<String, ?> paramMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        String param = "";
        Iterator<String> it = paramMap.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            param += key + "=" + paramMap.get(key);
            if (it.hasNext())
                param += "&";
        }
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String uploadPostLocal(String url, String path) {
        try {
            File file = new File(path);
            URL urlObj = new URL(url);
            HttpsURLConnection connection = (HttpsURLConnection) urlObj.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            String boundary = "" + System.currentTimeMillis();
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("Charset", "utf-8");
            StringBuilder sb = new StringBuilder();
            sb.append("--");
            sb.append(boundary);
            sb.append("\r\n");
            sb.append("Content-Disposition:form-data;name=\"entity.media\";filename=\"").append(file.getName()).append("\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            OutputStream out = connection.getOutputStream();
            InputStream is = new FileInputStream(file);
            log.info(sb.toString());
            out.write(sb.toString().getBytes());

            byte[] b = new byte[1024];
            int len;
            while ((len = is.read(b)) != -1) {
                out.write(b, 0, len);
            }

            String foot = "\r\n--" + boundary + "--\r\n";
            out.write(foot.getBytes());
            out.flush();
            out.close();

            InputStream ris = connection.getInputStream();
            StringBuilder resp = new StringBuilder();
            while ((len = ris.read(b)) != -1) {
                resp.append(new String(b, 0, len));
            }
            return resp.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String uploadPostUrl(String url, String fileUrl) {
        try {

            URL urlObj = new URL(url);
            HttpsURLConnection connection = (HttpsURLConnection) urlObj.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            String boundary = "" + System.currentTimeMillis();
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("Charset", "utf-8");
            StringBuilder sb = new StringBuilder();
            sb.append("--");
            sb.append(boundary);
            sb.append("\r\n");
            sb.append("Content-Disposition:form-data;name=\"entity.media\";filename=\"").append(System.currentTimeMillis()).append(".png\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            OutputStream out = connection.getOutputStream();
            InputStream is = getStreamByUrl(fileUrl);
//            InputStream is=  new ByteArrayInputStream(( requestByProxy(fileUrl,null,null)));
            log.info(sb.toString());
            out.write(sb.toString().getBytes());

            byte[] b = new byte[1024];
            int len;
            while ((len = is.read(b)) != -1) {
                out.write(b, 0, len);
            }

            String foot = "\r\n--" + boundary + "--\r\n";
            out.write(foot.getBytes());
            out.flush();
            out.close();

            InputStream ris = connection.getInputStream();
            StringBuilder resp = new StringBuilder();
            while ((len = ris.read(b)) != -1) {
                resp.append(new String(b, 0, len));
            }
            return resp.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static InputStream getStreamByUrl(String url) {
        try {
            URL urlObj = new URL(url);
            URLConnection connection = urlObj.openConnection();
            return connection.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String get(String url) {
        try {
            URL urlObj = new URL(url);
            URLConnection connection = urlObj.openConnection();
            InputStream is = connection.getInputStream();
            byte[] b = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = is.read(b)) != -1) {
                sb.append(new String(b, 0, len));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String sendPostERNIE(String url, String data) {
        try {
            URL urlObj = new URL(url);
            URLConnection connection = urlObj.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            connection.setRequestProperty("Accept-Charset", "utf-8");

            connection.setDoOutput(true);
            connection.setDoInput(true);
            if (data != null) {
                OutputStream os = connection.getOutputStream();
                os.write(data.getBytes());
                os.close();
            }
            InputStream is = connection.getInputStream();
            byte[] b = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = is.read(b)) != -1) {
                sb.append(new String(b, 0, len));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object requestByProxy(String inUrl,HashMap<String, Object> headerMap,String data) throws Exception {
        try {
            //设置代理
//            System.setProperty("http.proxyHost", "175.178.230.75");
//            System.setProperty("http.proxyPort", "7890");
//            System.setProperty("https.proxyHost", "175.178.230.75");
//            System.setProperty("https.proxyPort", "7890");
            System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
            System.setProperty("jdk.http.auth.proxying.disabledSchemes", "");
            Authenticator.setDefault(new BasicAuthenticator("153578456","handsomeboy666"));
            SocketAddress address = new InetSocketAddress("proxy.golxen.com", 7890);
            Proxy proxy = new Proxy(Proxy.Type.HTTP,address); // http 代理

            URL url = new URL(inUrl);
            URLConnection connection = url.openConnection(proxy);
//            URLConnection connection = url.openConnection();
//            connection.setRequestProperty("Proxy-Authorization","Basic " + Base64.encode("153578456:handsomeboy666".getBytes()));
//            connection.setRequestProperty("Proxy-Authorization","Basic " + Base64.encode("153578456:handsomeboy666"));
            if (headerMap!=null){
                for (Map.Entry<String, Object> item : headerMap.entrySet()) {
                    connection.setRequestProperty(item.getKey(),item.getValue().toString());//设置header
                }
            }
            connection.setDoOutput(true);
            connection.setDoInput(true);
            if (data != null) {
                OutputStream os = connection.getOutputStream();
                os.write(data.getBytes(StandardCharsets.UTF_8));
                os.close();
            }
            connection.connect();

            InputStream is = connection.getInputStream();
            //将字节流转化成字符流，并指定字符集
            InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
//        byte[] b = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = isr.read()) != -1) {
                sb.append((char) len);
            }
//            log.info(sb.toString());
            return sb;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            throw e;
        }
//        return null;
    }


    public static class BasicAuthenticator extends Authenticator {
        String userName;
        String password;

        public BasicAuthenticator(String userName, String password) {
            this.userName = userName;
            this.password = password;
        }
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password.toCharArray());
        }

    }

    public static Object request(String inUrl,HashMap<String, Object> headerMap,String data) throws Exception {
        URL url = new URL(inUrl);

        URLConnection connection = url.openConnection();

        if (headerMap!=null){
            for (Map.Entry<String, Object> item : headerMap.entrySet()) {
                connection.setRequestProperty(item.getKey(),item.getValue().toString());//设置header
            }
        }
        connection.setDoOutput(true);
        connection.setDoInput(true);
        if (data != null) {
            OutputStream os = connection.getOutputStream();
            os.write(data.getBytes(StandardCharsets.UTF_8));
            os.close();
        }
        connection.connect();

        InputStream is = connection.getInputStream();
        //将字节流转化成字符流，并指定字符集
        InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
        int len;
        StringBuilder sb = new StringBuilder();
        while ((len = isr.read()) != -1) {
            sb.append((char) len);
        }
        return sb.toString();
    }
}
